<?php

defined( 'PDNS_AUTH' ) or die( "Unauthorized" );

class zoneController extends Controller{
	public function action( $action ){
		switch( $action ){
			case 'add':
				$this->displayView( 'add' );
			break;
			case 'delete':
				$this->delete();
			break;
			case 'edit':
				$this->edit();
			break;
			case 'savenew':
				$this->savenew();
			break;
			case 'save':
				$this->save();
			break;
			case 'show':
			default:
				if( Request::getDomain('zone_id') )
					$this->show();
				else
					$this->displayView( 'query' );
			break;
		}
	}

	/**
	 *  deletes a domain
	 */
	protected function delete(){
		$model = $this->getModel();
		$model->load();
		$model->delete();
	}

	protected function edit(){
		$model = $this->getModel();
		$model->load();
		$this->displayView( 'edit', $model );
	}

	/**
	 *  Creates a new domain
	 *
	 *  @todo logic for model data assigning should be done in the model
	 */
	protected function savenew(){
		$domain = Request::getDomain('domain');
		$skel = Request::getDomain('skel');
		$db = DB::getInstance();
		
		$exists = $db->fetch_object( "SELECT id, name FROM domains WHERE name='$domain'" );

		if( $exists ){
			Message::warn( "Domain $domain already exists." );
			$this->action( 'add' );
			return;
		}
		
		$model = $this->getModel();

		if( $skel ){
			// create new domain from template
			$model->load( $skel );

			// replace skeleton values with new domain name
			// todo: move logic to model
			$model->domain->id = null;
			$model->domain->name = $domain;

			foreach( $model->records as &$r ){
				$r->id = null;
				$r->name = str_replace( $skel, $domain, $r->name );
				$r->content = str_replace( $skel, $domain, $r->content );
			}
		}
		else{
			// create new basic model
			// todo: move logic to model
			$model->domain = (object) array( 'id'=>null, 'name'=>$domain );
			$model->records = array();
		}

		// save the new domain
		$model->store();

		$db->log( 'action', $domain, 'Added' ); 
		Message::status( "{$model->domain->name} added." );

		// execute show action
		Request::set( 'zone_id', $domain );
		$this->action( 'show' );
	}

	protected function save(){
		$model = $this->getModel();
		$model->load();
		$model->bind( $_POST );
		$model->store();

		$db = DB::getInstance();
		$db->log( 'action', $model->domain->name, 'Modified' );

		Message::status( "{$model->domain->name} saved." );
		$this->action( 'show' );
	}

	protected function show(){
		$model = $this->getModel();
		try{
			$model->load();
		}
		catch( Exception $e ){
			echo $e;
			Message::warn( 'Domain does not exist' );
			$this->displayVIew( 'query' );
			return;
		}
		
		$h2 = <<<EOD
<!-- Domain ID: {$model->domain->id} -->
<h2>{$model->domain->name}</h2>
EOD;
		Output::setOutput( 'h2', $h2 );

		Actions::addAction( 'Edit', "action=edit&zone_id={$model->domain->id}" );
		Actions::addAction( 'Delete', "action=delete&zone_id={$model->domain->id}" );
		
		$this->displayView( 'show', $model );
	}
}

